<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/7/22
 * Time: 14:22
 */
namespace app\api\controller\v1;

use app\api\model\Smsapi as Smsapis;
use app\admin\model\Client as Clients;
use app\admin\model\Smssign as Smssigns;
use app\admin\model\Smscfg as Smscfgs;
use app\admin\model\Smsrequestlog as Smsrequestlogs;
use app\admin\model\Smstasklog as Smstasklogs;
use app\admin\model\Smstimelog as Smstimelogs;
use app\admin\model\Smscp as Smscps;
use app\common\Common;
use think\Request;
use think\Config;

class Smsapi extends Common{
    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(){
        try {
            $data   = json_decode(file_get_contents('php://input'),true);
            $validate = validate('Smsapi');
            if (!$validate->check($data)) {
                abort(409,$validate->getError());
            }else {
                //检查客户是否存在或冻结
                $client = Clients::get(['appid' => $data['appid'],'status'=>1]);

                if(!$client){
                    abort(409,'客户不存在或禁用');
                }elseif($client['enc_appkey'] != $data['appkey']){
                    abort(409,'接口秘钥错误');
                }else{
                    $client_id      = $client['id'];
                    $task_id        = $data['task_id'];
                    $order_id       = $data['order_id'];
                    $origin_id      = $data['origin_id'];
                    $mobile         = $data['mobile'];
                    $signature      = $data['signature'];
                    $content        = $data['content'];
                    $sms_type       = $data['sms_type'];
                    $ext_code       = $data['ext_code'];
                    $at_time        = $data['at_time'];
                    //初始化
                    //本平台的序列号
                    if(empty($task_id)){
                        $task_id = get_serial_number();
                    }
                    if(empty($order_id)){
                        $order_id = get_serial_number();
                    }
                    if(empty($origin_id)){
                        $origin_id = 1;
                    }
                    if(empty($sms_type)){
                        $sms_type = 2; //默认为2，普通业务短信
                    }
                    $signature = str_replace("【","",$signature);
                    $signature = str_replace("】","",$signature);

                    //计算短信条数（中文和英文均按1个“字”计算）,短信内容=签名+内容
                    $detail = '【'.$signature.'】'.$content;
                    $len = mb_strlen($detail,'UTF-8');
                    //短信内容字数不能500个字或不能为空
                    if($len>500){
                        abort(409,'短信内容不能超过500个字或字符');
                    }elseif($len <= 70){
                        $sms_size = 1;
                    }else{
                        $f = $len/67;
                        $sms_size = ceil($f);
                    }

                    //需要查询数据库
                    //查询签名是否备案
                    if(!(Smssigns::get(['client_id' => $client_id,'signature'=>$signature,'status'=>1]))){
                        abort(409,'签名未备案，不合法');
                    }
                    if(!($cfg = Smscfgs::get(['client_id' => $client_id,'sms_type_id'=>$sms_type,'status'=>1]))){
                        abort(409,'未开通此业务');
                    }
                    if ( strpos( $cfg['bound_ip'],get_client_ip()) ===false){
                        abort(409,'客户端IP与绑定的不符');
                    }
                    $errorMobiles = [];
                    $validMobiles = [];
                    //号码过滤
                    foreach($mobile as $v){
                        if(!checkMobile($v)){
                            array_push($errorMobiles,$v);
                            continue;
                        }elseif((Smsrequestlogs::get(function($query) use($client_id,$sms_type,$v){
                                $from = strtotime(date('Ymd',time()).'00:00:00');
                                $where1['create_time']  = ['BETWEEN',[$from,time()]];
                                $query->where(['client_id'=>$client_id,'sms_type_id'=>$sms_type,'mobile'=>$v])
                                ->where($where1)->count();
                            })) >= $cfg['limit_day']){
                                array_push($errorMobiles,$v);
                                continue;
                        }elseif((Smsrequestlogs::get(function($query) use($client_id,$sms_type,$v){
                                $from = strtotime(date("Y-m-01 00:00:00",time()));
                                $where1['create_time']  = ['BETWEEN',[$from,time()]];
                                $query->where(['client_id'=>$client_id,'sms_type_id'=>$sms_type,'mobile'=>$v])
                                ->where($where1)->count();
                            })) >= $cfg['limit_month']){
                                array_push($errorMobiles,$v);
                                continue;
                        }else{
                            array_push($validMobiles,$v);
                        }
                    }
                    if(empty($validMobiles)){
                        abort(409,'号码错误或超限');
                    }
                    if(count($validMobiles) > $cfg['balance']){
                        abort(409,'余额不足');
                    }
                    //提交入库
                    $bat = array(
                        'client_id'     => $client_id,
                        'task_id'       => $task_id,
                        'order_id'      => $order_id,
                        'origin_id'     => $origin_id,
                        'mobile'        => implode(',',$validMobiles),
                        'signature'     => $signature,
                        'content'       => $content,
                        'sms_type_id'   => $sms_type,
                        'sms_size'      => $sms_size,
                        'ext_code'      => $ext_code,
                        'at_time'       => $at_time,
                        'ip'            => get_client_ip(),
                        'create_time'   => time(),
                    );
                    Smstasklogs::create($data);
                    $num = 0; //记录插入的短信条数
                    foreach ($validMobiles as $vo){
                        $bat['mobile'] = $vo;
                        if($sms_size == 1){
                            $bat['request_id'] = $task_id.$vo.$sms_size;
                            Smsrequestlogs::create($data);
                            $num += 1;
                        }elseif ($sms_size > 1){
                            $l = 67;
                            $index = 0;
                            for($j = 1;$j<=$sms_size;$j++){
                                $con = mb_substr($detail,$index,$l,'UTF-8');
                                if($j == 1){
                                    $l_sign = mb_strlen('【'.$signature.'】','UTF-8');
                                    $l_z = $l-$l_sign;
                                    $con = mb_substr($con,$l_sign,$l_z,'UTF-8');
                                }
                                $bat['content'] = $con;
                                $bat['sms_index'] = $j;
                                $bat['request_id'] = $task_id.$vo.$j;
                                Smsrequestlogs::create($data);
                                $num += 1;
                                $index = $index+$l;
                            }
                        }
                    }
                    //扣除余额
                    Smscfgs::where('id='.$cfg['id'])->setDec('balance', abs($num));
                    //如果定时时间不为空，则入库，待定时发送，
                    if($at_time){
                        $time = array(
                            'client_id'     => $client_id,
                            'task_id'       => $task_id,
                            'order_id'      => $order_id,
                            'origin_id'     => $origin_id,
                            'mobile'        => implode(',',$validMobiles),
                            'signature'     => $signature,
                            'content'       => $content,
                            'sms_type_id'   => $sms_type,
                            'sms_size'      => $sms_size,
                            'ext_code'      => $ext_code,
                            'at_time'       => $at_time,
                            'ip'            => get_client_ip(),
                            'create_time'   => time(),
                        );
                        $result = Smstimelogs::create($time);
                        return json(['code'=>0,'errorMsg'=>'success','data'=>[]]);
                    }
                    //如果是同步提交，则直接调用供应商api
                    if (Config::get('BUY_SYNC')){
                        //查找供应商
                        if(!($provider = Smscps::get(['client_id'=>$client_id,'client_sms_type_id'=>$sms_type,'is_valid'=>1]))){
                            //退款
                            Smscfgs::where('id='.$cfg['id'])->setInc('balance', abs($num));
                            abort(409,'未找到供应商');
                        }
                        //提交数据给供应商
                        $req2 = array(
                            'client_id'     => $client_id,
                            'task_id'       => $task_id,
                            'order_id'      => $order_id,
                            'origin_id'     => $origin_id,
                            'mobile'        => $mobile,
                            'provider_id'   => $provider['provider_id'],
                            'signature'     => $signature,
                            'content'       => $content,
                            'at_time'       => $at_time,
                            'ext_code'      => $cfg['ext_code'].$ext_code,
                            'sms_size'      => $sms_size,
                            'sms_type'      => $sms_type,
                            'num'           => $num,
                            'cfg_id'        => $cfg['id']
                        );
                        $rt = sendSms($req2);
                        //将结果反馈给客户
                        if ($rt['status'] == 0){
                            return json(['code'=>0,'errorMsg'=>'success','data'=>[]]);
                        }elseif ($rt['status'] == 98){
                            abort(98,'系统忙');
                        }else{
                            abort(409,'失败');
                        }
                    }
                }
            }
        } catch (\Exception $e) {
            // 捕获异常并转发为HTTP异常
            return abort(404, $e->getMessage());
        }
    }
}